package cn.tools.vaildator.config;

/**
 * @author: e
 * @date: 2021/12/8
 * @description:
 */


import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理
 */
//接口拦截器，指定只要在类上加了RestController，或者Controller的类，都被其拦截
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//返回数据为json格式
@ResponseBody
public class ExceptionConfiguration {
    /**
     * @author: keno
     * @date:   2021/12/8
     * @description:
     * @ExceptionHandler异常处理器，标注在方法上表示异常出现后，由此方法进行处理
     * 这里我们主要抓的异常是注解约束的异常，所以我们只抓下面两种异常
     * ConstraintViolationException
     * BindException
     */
    @ExceptionHandler({ConstraintViolationException.class,BindException.class})
    public String validateException(Exception ex, HttpServletRequest request, HttpServletResponse response) {
        String message="";

        //如果异常是这种类型的异常，则将ex强转为这种异常类型，Exception是所有异常的父类，所以这里由父类转为对应子类进行处理
        if(ex instanceof ConstraintViolationException){
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex;

            //获取出异常的消息集合
            ConstraintViolation<?> next = constraintViolationException.getConstraintViolations().iterator().next();
            message = next.getMessage();

        }else if(ex instanceof BindException){
            BindException bindException = (BindException) ex;
            message = bindException.getBindingResult().getFieldError().getDefaultMessage();
        }


        return message;
    }
}